package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author fengzhu
 * @since 2024-10-10
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            // 生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("发送的验证码:{}", code);

            // 省略短信发送逻辑，假设发送成功
            user.setId(1L);
            session.setAttribute(phone, code);
            session.setAttribute("user",user.getId());
            log.info("id是{}",user.getId());// 将验证码存储到 session 中
            return R.success("验证码发送成功");
        }
        return R.error("发送验证码失败，手机号不能为空");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = map.get("code");

        // 获取 session 中的验证码
        Object sessionCode = session.getAttribute(phone);

        if (sessionCode != null && sessionCode.equals(code)) {
            // 验证成功，查询用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);

            // 用户不存在则注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }

            // 保存登录用户 ID
            session.setAttribute("user", user.getId());
            return R.success(user);
        } else {
            return R.error("验证码错误或已失效");
        }
    }
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return  R.success("成功");
    }
}

